/**
 * API服务层
 * 
 * 封装所有与后端API的交互逻辑
 */

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { 
  ApiResponse, 
  PaginationParams, 
  PaginatedResponse,
  DataSourceConfig,
  ConnectionTestResult,
  SchemaInfo,
  ApiDefinition,
  ComponentHealth,
  SystemMetrics,
  PluginInfo,
  UserInfo
} from '@/types';

// ============================================================================
// API客户端配置
// ============================================================================

/** API基础配置 */
const API_CONFIG = {
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
};

/** 创建API客户端实例 */
class ApiClient {
  private client: AxiosInstance;

  constructor() {
    this.client = axios.create(API_CONFIG);
    this.setupInterceptors();
  }

  /** 设置请求和响应拦截器 */
  private setupInterceptors() {
    // 请求拦截器 - 添加认证token
    this.client.interceptors.request.use(
      (config) => {
        const token = localStorage.getItem('auth-token');
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => Promise.reject(error)
    );

    // 响应拦截器 - 统一错误处理
    this.client.interceptors.response.use(
      (response: AxiosResponse<ApiResponse>) => {
        // 检查业务层面的错误
        if (!response.data.success) {
          throw new Error(response.data.message || '请求失败');
        }
        return response;
      },
      (error) => {
        // 处理HTTP错误
        if (error.response?.status === 401) {
          // 未授权，清除token并跳转到登录页
          localStorage.removeItem('auth-token');
          window.location.href = '/login';
        } else if (error.response?.status === 403) {
          throw new Error('权限不足');
        } else if (error.response?.status >= 500) {
          throw new Error('服务器内部错误');
        } else if (error.code === 'ECONNABORTED') {
          throw new Error('请求超时');
        } else if (!error.response) {
          throw new Error('网络连接失败');
        }
        
        throw error;
      }
    );
  }

  /** 通用GET请求 */
  async get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.client.get<ApiResponse<T>>(url, config);
    return response.data.data!;
  }

  /** 通用POST请求 */
  async post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.client.post<ApiResponse<T>>(url, data, config);
    return response.data.data!;
  }

  /** 通用PUT请求 */
  async put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.client.put<ApiResponse<T>>(url, data, config);
    return response.data.data!;
  }

  /** 通用DELETE请求 */
  async delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.client.delete<ApiResponse<T>>(url, config);
    return response.data.data!;
  }

  /** 分页查询 */
  async getPaginated<T = any>(
    url: string, 
    params: PaginationParams & Record<string, any> = { page: 1, pageSize: 20 }
  ): Promise<PaginatedResponse<T>> {
    return this.get<PaginatedResponse<T>>(url, { params });
  }
}

// 创建全局API客户端实例
const apiClient = new ApiClient();

// ============================================================================
// 认证相关API
// ============================================================================

export const authApi = {
  /** 用户登录 */
  login: async (username: string, password: string): Promise<{ user: UserInfo; token: string }> => {
    return apiClient.post('/auth/login', { username, password });
  },

  /** 用户登出 */
  logout: async (): Promise<void> => {
    return apiClient.post('/auth/logout');
  },

  /** 获取当前用户信息 */
  getCurrentUser: async (): Promise<UserInfo> => {
    return apiClient.get('/auth/me');
  },

  /** 刷新token */
  refreshToken: async (): Promise<{ token: string }> => {
    return apiClient.post('/auth/refresh');
  },
};

// ============================================================================
// 数据源相关API
// ============================================================================

export const dataSourceApi = {
  /** 获取数据源列表 */
  getDataSources: async (params?: PaginationParams): Promise<PaginatedResponse<DataSourceConfig>> => {
    return apiClient.getPaginated('/datasources', params);
  },

  /** 获取数据源详情 */
  getDataSource: async (id: string): Promise<DataSourceConfig> => {
    return apiClient.get(`/datasources/${id}`);
  },

  /** 创建数据源 */
  createDataSource: async (dataSource: Omit<DataSourceConfig, 'id' | 'createdAt' | 'updatedAt'>): Promise<DataSourceConfig> => {
    return apiClient.post('/datasources', dataSource);
  },

  /** 更新数据源 */
  updateDataSource: async (id: string, dataSource: Partial<DataSourceConfig>): Promise<DataSourceConfig> => {
    return apiClient.put(`/datasources/${id}`, dataSource);
  },

  /** 删除数据源 */
  deleteDataSource: async (id: string): Promise<void> => {
    return apiClient.delete(`/datasources/${id}`);
  },

  /** 测试数据源连接 */
  testConnection: async (id: string): Promise<ConnectionTestResult> => {
    return apiClient.post(`/datasources/${id}/test`);
  },

  /** 获取数据源Schema */
  getSchema: async (id: string): Promise<SchemaInfo> => {
    return apiClient.get(`/datasources/${id}/schema`);
  },

  /** 执行查询 */
  executeQuery: async (id: string, query: string, params?: Record<string, any>): Promise<any> => {
    return apiClient.post(`/datasources/${id}/query`, { query, params });
  },
};

// ============================================================================
// API管理相关API
// ============================================================================

export const apiManagementApi = {
  /** 获取API列表 */
  getApis: async (params?: PaginationParams): Promise<PaginatedResponse<ApiDefinition>> => {
    return apiClient.getPaginated('/apis', params);
  },

  /** 获取API详情 */
  getApi: async (id: string): Promise<ApiDefinition> => {
    return apiClient.get(`/apis/${id}`);
  },

  /** 创建API */
  createApi: async (api: Omit<ApiDefinition, 'id' | 'createdAt' | 'updatedAt'>): Promise<ApiDefinition> => {
    return apiClient.post('/apis', api);
  },

  /** 更新API */
  updateApi: async (id: string, api: Partial<ApiDefinition>): Promise<ApiDefinition> => {
    return apiClient.put(`/apis/${id}`, api);
  },

  /** 删除API */
  deleteApi: async (id: string): Promise<void> => {
    return apiClient.delete(`/apis/${id}`);
  },

  /** 测试API */
  testApi: async (id: string, params?: Record<string, any>): Promise<any> => {
    return apiClient.post(`/apis/${id}/test`, params);
  },

  /** 发布API */
  publishApi: async (id: string): Promise<ApiDefinition> => {
    return apiClient.post(`/apis/${id}/publish`);
  },

  /** 下线API */
  unpublishApi: async (id: string): Promise<ApiDefinition> => {
    return apiClient.post(`/apis/${id}/unpublish`);
  },
};

// ============================================================================
// 监控相关API
// ============================================================================

export const monitoringApi = {
  /** 获取系统指标 */
  getSystemMetrics: async (): Promise<SystemMetrics> => {
    return apiClient.get('/monitoring/system');
  },

  /** 获取组件健康状态 */
  getComponentHealth: async (): Promise<ComponentHealth[]> => {
    return apiClient.get('/monitoring/health');
  },

  /** 获取指标历史数据 */
  getMetricsHistory: async (
    metric: string, 
    startTime: number, 
    endTime: number, 
    interval?: string
  ): Promise<any[]> => {
    return apiClient.get('/monitoring/metrics/history', {
      params: { metric, startTime, endTime, interval }
    });
  },

  /** 获取Prometheus指标 */
  getPrometheusMetrics: async (): Promise<string> => {
    const response = await axios.get('/metrics', {
      headers: { 'Accept': 'text/plain' }
    });
    return response.data;
  },
};

// ============================================================================
// 插件相关API
// ============================================================================

export const pluginApi = {
  /** 获取插件列表 */
  getPlugins: async (): Promise<PluginInfo[]> => {
    return apiClient.get('/plugins');
  },

  /** 获取插件详情 */
  getPlugin: async (id: string): Promise<PluginInfo> => {
    return apiClient.get(`/plugins/${id}`);
  },

  /** 安装插件 */
  installPlugin: async (pluginFile: File): Promise<PluginInfo> => {
    const formData = new FormData();
    formData.append('plugin', pluginFile);
    return apiClient.post('/plugins/install', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
  },

  /** 启用插件 */
  enablePlugin: async (id: string): Promise<PluginInfo> => {
    return apiClient.post(`/plugins/${id}/enable`);
  },

  /** 禁用插件 */
  disablePlugin: async (id: string): Promise<PluginInfo> => {
    return apiClient.post(`/plugins/${id}/disable`);
  },

  /** 卸载插件 */
  uninstallPlugin: async (id: string): Promise<void> => {
    return apiClient.delete(`/plugins/${id}`);
  },

  /** 更新插件配置 */
  updatePluginConfig: async (id: string, config: Record<string, any>): Promise<PluginInfo> => {
    return apiClient.put(`/plugins/${id}/config`, config);
  },
};

// ============================================================================
// 缓存相关API
// ============================================================================

export const cacheApi = {
  /** 获取缓存统计 */
  getCacheStats: async (): Promise<any> => {
    return apiClient.get('/cache/stats');
  },

  /** 清空缓存 */
  clearCache: async (pattern?: string): Promise<void> => {
    return apiClient.post('/cache/clear', { pattern });
  },

  /** 获取缓存键列表 */
  getCacheKeys: async (pattern?: string): Promise<string[]> => {
    return apiClient.get('/cache/keys', { params: { pattern } });
  },

  /** 删除缓存键 */
  deleteCacheKey: async (key: string): Promise<void> => {
    return apiClient.delete(`/cache/keys/${encodeURIComponent(key)}`);
  },
};

// ============================================================================
// 导出默认API客户端
// ============================================================================

export default apiClient;
